<?php
class SdpSortHelper{
	var $idx=0;
	var $_request=null;
	public function __construct($default=0){
		$this->idx=$default;
		$this->_request=array();
	}
	public function parse($aRequestArr,$ignoredKeys=null){
		if ( !(is_array($ignoredKeys)) ){
			$ignoredKeys=null;
		}
		if (!empty($aRequestArr)){
			foreach ($aRequestArr as $key => $value){
				if ( $key=="sort" ){
					$this->idx=intval($value);
				}else
				if ( (null == $ignoredKeys) || (!(in_array($key,$ignoredKeys))) ){
					$this->_request[$key]=$value;
				}
			}
		}
	}
	public function direction($index){
		if (abs($this->idx) == $index) {
			return -$this->idx;
		}
		return $index;
	}
	public function indexToHiddenField(){
		return "<input type='hidden' name='sort' value='{$this->idx}' />";
	}
	public function getSortIndex(){
		return abs($this->idx);
	}
	public function sortAscending(){
		return ( 0 < $this->idx);
	}
	public function sortDescending(){
		return ( 0 > $this->idx);
	}
	public function mark($index){
		if (abs($this->idx) == $index) {
			return ((0 < $this->idx)?("&#9660;"):("&#9650;"));
		}
		return "";
	}
	public function getRequest(){
		$ret_str="";
		foreach ($this->_request as $key => $value){
			$ret_str.="&{$key}={$value}";
		}
		$ret_str=substr($ret_str,1);
		return $ret_str;
	}
	public function getHref($aSortIndex){
		$result="?";
		$result.=$this->getRequest();
		$result.="&sort={$this->direction($aSortIndex)}";
		return $result;
	}
	public function getSortLink($aIdx,$aName){
		$ret_str=$aName;
		if (intval($aIdx)==$aIdx){
			$ret_str="<a href='{$this->getHref($aIdx)}'>{$aName}&#160;{$this->mark($aIdx)}</a>";
		}
		return $ret_str;
	}
	public function setSortIndex($aIdx,$asc=true){
		$this->idx=abs($aIdx);
		$this->idx=(($asc)?($this->idx):(-$this->idx));
	}
}
?>